#include "autoload.hpp"
#include <fstream>
#include <getopt.h>
#include <iostream>

using namespace std;

static string _merge_once(json& con_json, string patch_file)
{
    cout << "patch file:" << patch_file << endl;

    try {
        std::ifstream f2(patch_file);
        auto          pat_json = json::parse(f2);

        con_json.merge_patch(pat_json);
        cout << "patch file:" << patch_file << " ok" << endl;
        return patch_file.substr(patch_file.find_last_of("/\\") + 1);
    } catch (...) {
        cout << "patch file:" << patch_file << " failed" << endl;
    }
    return "";
}

static void merge_once(string& config_file, int& succcnt, json& con_json, string patch_file)
{
    string addname = _merge_once(con_json, patch_file);
    if (addname != "") {
        succcnt++;
        config_file += ".";
        config_file += addname;
    }
}

string merge_file(string config_file, json& usr)
{
    std::ifstream f1(config_file);
    auto          con_json = json::parse(f1);
    int           succcnt  = 0;
    if (usr.is_array()) {
        for (auto pp : usr) {
            merge_once(config_file, succcnt, con_json, pp);
        }
    } else {
        merge_once(config_file, succcnt, con_json, usr);
    }

    if (!succcnt) {
        throw std::runtime_error("can't patch any file");
    }
    std::ofstream fout(config_file);
    fout << con_json << endl;
    return config_file;
}
